package com.mypack.crm.service.customer.impl;

import com.github.pagehelper.PageHelper;
import com.mypack.crm.constants.EnumDeleteFlag;
import com.mypack.crm.constants.EnumStatus;
import com.mypack.crm.dto.customer.CustomerDTO;
import com.mypack.crm.dto.customer.CustomerSearchDTO;
import com.mypack.crm.entity.CrmCustomer;
import com.mypack.crm.mapper.CustomerMapper;
import com.mypack.crm.service.customer.CustomerService;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private MapperFacade mapperFacade;

    @Override
    public void add(CustomerDTO customerDTO) {

        CrmCustomer crmCustomer = mapperFacade.map(customerDTO, CrmCustomer.class);
        crmCustomer.setStatus(EnumStatus.ACTIVE.getCode());
        crmCustomer.setDeleteFlag(EnumDeleteFlag.NO.getCode());
        crmCustomer.setCreateTime(new Date());

        customerMapper.insert(crmCustomer);
    }

    @Override
    public void update(CustomerDTO customerDTO) {

        CrmCustomer crmCustomer = mapperFacade.map(customerDTO, CrmCustomer.class);

        crmCustomer.setUpdateTime(new Date());

        customerMapper.updateById(crmCustomer);
    }

    @Override
    public List<CustomerDTO> list(CustomerSearchDTO customerSearchDTO, boolean isPage) {

        if (isPage) {
            PageHelper.startPage(customerSearchDTO.getPageNum(), customerSearchDTO.getPageSize());
        }

        return customerMapper.listCustomer(customerSearchDTO);
    }

    @Override
    public CustomerDTO queryById(Integer id) {
        if (id == null) {
            return null;
        }
        CrmCustomer crmCustomer = customerMapper.selectById(id);

        if (null == crmCustomer) {
            return null;
        }

        CustomerDTO customerDTO = mapperFacade.map(crmCustomer, CustomerDTO.class);

        return customerDTO;
    }
}
